import { observable, action, autorun, toJS } from 'mobx';
import * as  Apis from '../apis/govern';
import { ListStore } from './listStore';
import { WeaForm,WeaTableNew } from 'comsMobx';
import { message, Modal } from "antd";
import { ModelStore } from './modelStore';
import { ModalConfirmStore } from './modalConfirmStore';
import GetFormJson from '../util/getFormJson';
import { WeaLocaleProvider,WeaTools } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const {TableStore} = WeaTableNew;

export default class TaskStore extends ListStore {
    @observable tasklabels = {};
    @observable condition = [];
    @observable conditionNum = [];
    @observable status = {
        loading: false,
        showSlideModal: false
    }
    @observable modelType = "";
    @observable id = "";
    @observable content = "";
    //@observable visible = false;
    @observable searchPanelVisible = false;
    @observable modelStore = new ModelStore();
    @observable confirmVisible = false;
    @observable modalConfirmStore = new ModalConfirmStore();
    @observable slideStatu = {
        id: "",
        rightMenu: [],
        quickBtn: [],
        progress: 0
    };
    @observable title = "";
    @observable dataType = false;// 控制页面刷新
    apisType = Apis.getMyTaskList; // 控制table的api
    dealtype = null; //为1协办存在子列表,为0主办存在子列表
    listType = null; // 已完成任务标志,finish为已完成任务
    isSelect = false;//顶部表单select框key值改变
    @observable isSuperSearch = false;//点击pre高级搜索
    @observable selectedTreeKey = 0;
    @observable treeData = [];
    @observable hasTaskRight = false;//有详情权限
    @observable noDoAgain = false;//防止任务查询结果页面二次执行搜索方法
    @observable columnsNum = 0;//table表格列数
    @observable tabSelectedKey = '0';//任务台账的tab的key
    @observable cubeLayoutParame = {};//装载布局请求入参
    @observable Card = {};
    @observable isTreeShow = true;//督办类型树是否默认展示

    @action
    setDataType(dataType) {
        this.dataType = dataType;
        this.dealtype = null;
        this.listType = null;
        this.noDoAgain = false;
        if (dataType == "0") {
            this.title = `${getLabel('387980', '我的关注')}`;
            this.apisType = Apis.getAttentionTaskList;
        } else if (dataType == "1") {
            this.title = `${getLabel('383349,33046', '任务查询结果')}`;//任务查询
            this.apisType = Apis.getMyTaskList;
            this.noDoAgain = true;
        } else if (dataType == "2") {
            this.title = `${getLabel('388805', '我的协办')}`;
            this.dealtype = "1";
            this.apisType = Apis.getMyTaskList;
        } else if (dataType == "3") {
            this.title = `${getLabel('15289', '已完成任务')}`;//归档
            this.listType = "finish";
            this.apisType = Apis.getMyTaskList;
        } else if (dataType == "4") {
            this.title = `${getLabel('388804', '我的主办')}`;
            this.dealtype = "0";
            this.apisType = Apis.getMyTaskList;
        } else if (dataType == "5") {
            this.title = `${getLabel('508062', '任务台账')}`;
            this.dealtype = "0";
            this.apisType = Apis.getTaskAccount;
        }
    }
    constructor(props) {
        super(props);
        window.showTaskSpaModel = this.showTaskSpaModel;
        this.doSearch = this.doSearch.bind(this);
        this.setSearchPanelVisible = this.setSearchPanelVisible.bind(this);
        this.initSearchPanel = this.initSearchPanel.bind(this);
        this.getcolumnsNum = this.getcolumnsNum.bind(this);
        this.clear = this.clear.bind(this);
    }

    showTaskSpaModel = (id, modeType) => {
        this.id = id;
        this.modelType = modeType;
        this.modelStore.showSpaModel(id, modeType);
    }

    @action
    initTreeData() {
        Apis.getTreeDatas().then(data => {
            if (parseInt(data.status) == 1) {
                this.treeData = data.categotyData;
            } else {
                message.error(data.error);
            }
        }).catch(error => {
            message.error(error);
        });
    }

    @action
    getIsTreeShow() {
        Apis.getIsTreeShow().then(data => {
            if (parseInt(data.status) == 1) {
                this.isTreeShow = data.isTreeShow;
            } else {
                message.error(data.error);
            }
        }).catch(error => {
            message.error(error);
        });
    }

    //左侧树的点击事件
    @action
    setSelectedTreeKey = (key, apisType) => {
        this.apisType = apisType;
        if (key != this.selectedTreeKey) {
            this.status.loading = true;
            this.form.resetForm();
            this.selectedTreeKey = key;
            this.noDoAgain = false;//切换左侧树，table列表不切换18.12.25
            this.init({ "categoryid": key });
        }
    }

    @action
    onCollapse = (bool) => {
        this.isTreeShow = bool;
    }

    /**
     * 弹窗动作执行方法
     * @param {*} id
     * @param {*} modelType
     */
    @action
    showModel(id, modelType) {
        this.id = id;
        this.modelType = modelType;
        this.modelStore.handleShareDialog(true);
        this.modelStore.initModel(this.modelType, id);
        this.modelStore.form = new WeaForm();
    }
    /**
     * 弹窗动作执行方法
     * @param {*} id
     * @param {*} modelType
     */
    @action
    showconfirm(id, modelType, title, content) {
        this.id = id;
        this.modelType = modelType;
        this.modelStore.showConfirm({ id, modelType, title, content });
    }
    /**
     * 获取滑出页面信息
     * @param {*} params
     */
    @action
    getSlideCondition(params) {
        this.slideStatu.id = params.id;
        this.status.loading = true;
        let _this = this;
        Apis.getTaskInfo(params).then(data => {
            if (data.status == "1") {
                _this.mackCondition(data);
                 if(data.isopen === true){
                    this.cubeLayoutParame = data.data;
                  }
                this.slideStatu.rightMenu = data.rightMenu;
                this.slideStatu.quickBtn = data.quickBtn;
                this.slideStatu.progress = data.progress;
                this.status.loading = false;
            } else {
                message.error(getLabel('26161,389235', "没有任务内容"))
            }
        }).catch(error => {
            message.error(error);
        });
    }
    mackCondition(data) {
        let f = _.cloneDeep(data);
        let newData = GetFormJson.setFormJson(f, this.formSlide, "condition", ["remark"], [1, 2], [4, 11], [20, 13], this.getCondition, this, false);//事项阶段
        this.conditionNum = newData.condition;
        this.formSlide && !this.formSlide.isFormInit && this.formSlide.initFormFields(newData.condition);
    }
    @action
    getCondition(condition, _this) {
        _this.condition = condition;
    }
    @action
    setSearchPanelVisible(bool) {
        this.searchPanelVisible = bool;
    }
    @action
    setDoAgain(bool) {
        this.noDoAgain = bool;
    }
    /**
     * 初始化页面
     * @param isSuper  请求接口参数
     * @param isSuperPage  当前页面是否高级搜索页面
     * @param fromSuperPage  当前页面是否来自高级搜索页面
     */
    @action
    init(params, store) {
        this.isSuperSearch = _.has(params, 'isSuperSearch') ? params.isSuperSearch : false;
        //初始化顶部表单
        let newParams = { "isSuper": "0", "isSuperPage": false, "fromSuperPage": false, "dealtype": this.dealtype, "listType": this.listType, "categoryid": this.selectedTreeKey || params.selectedTreeKey, "isSelect": this.isSelect, "dataType": this.dataType, ...params };
        this.getTaskListConditions(newParams, store);
        // //初始化搜索面板
        if (_.has(params, 'projid')) {
            params.isSuperPage ? null : this.getSearchPanel(params);//任務台賬初始化高級搜索面板
        }
        //  params.isSuperPage ? null : (this.searchPanelVisible ? this.getSearchPanel() : null);//初始化不必要加载
        //初始化表格
        params.isSuperPage ? null : (this.noDoAgain ? null : this.doSearch(newParams));
        //初始化左侧树
        params.isSuperPage ? null : this.initTreeData();
        //清除数据
        this.clearFormFields();
    }
    @action
    initSearchPanel() {
        //初始化搜索面板
        this.searchPanelVisible ? this.getSearchPanel() : null;//初始化不必要加载
    }
    @action
    getTaskListConditions(params, store) {
        this.form = new WeaForm();
        this.formB = new WeaForm();
        this.status.loading = true;
        Apis.getTaskListConditions(params).then(data => {
            if (parseInt(data.status) == 1) {
                if (params.fromSuperPage || this.isSelect || this.selectedTreeKey) {
                    this.condition = data.searchCondition;
                    this.form && !this.form.isFormInit && this.form.initFormFields(data.searchCondition);
                } else if (params.isSuperPage) {//pre高级搜索
                    this.conditionNum = data.searchCondition;
                    this.formB && !this.formB.isFormInit && this.formB.initFormFields(data.searchCondition);
                }
            } else {
                message.error(data.error);
            }
            if (params.prjid) {//xk：任务台账权限判断
                store.hasTaskRight = data.isRight;
            }
            this.status.loading = false;
        })
            .catch(error => {
                message.error(error);
            });
    }
    /*
     * 顶部表单，select的key值改变，执行方法
    */
    @action
    handleChange() {
        this.isSelect = true;
        const searchParamsAd = this.form.getFormParams();
        const params = { "listType": this.listType, "dealtype": this.dealtype, "categoryid": this.selectedTreeKey, "isSelect": this.isSelect, "dataType": this.dataType, ...searchParamsAd };
        this.getTaskListConditions(params);
    }
    //初始化搜索面板
    @action
    getSearchPanel(params) {
        const newParams = { "isSuper": "1", "categoryid": this.selectedTreeKey, "dataType": this.dataType, "dealtype": this.dealtype };
        if(_.has(params,"selectedTreeKey")){
            newParams.categoryid = this.selectedTreeKey || params.selectedTreeKey 
        }
      
        this.formB = new WeaForm();
        Apis.getTaskListConditions(newParams).then(data => {
            if (parseInt(data.status) == 1) {
                this.conditionNum = data.searchCondition;
                this.formB && !this.formB.isFormInit && this.formB.initFormFields(data.searchCondition);
            } else {
                message.error(data.error);
            }
            this.status.loading = false;
        })
            .catch(error => {
                message.error(error);
            });
    }
    @action
    clearFormFields() {
        this.searchPanelVisible = false;
        this.form.resetForm();
        this.formB.resetForm();
        //this.apisType = Apis.getMyTaskList; // 19.1.24我的关注时接口请求不对
        //this.dealtype = null; //为1协办存在子列表,为0主办存在子列表
        //this.listType = null; // 已完成任务标志,finish为已完成任务
        this.isSelect = false;//顶部表单select框key值改变
        this.isSuperSearch = false;//点击pre高级搜索
    }
    @action
    doSearch(params) {//{ "isSuper":"0","isSuperPage":false,"fromSuperPage":true
        this.status.loading = true;
        if (params.isSuper && params.isSuper === "1") {
            this.noDoAgain = true;
        } else {
            this.noDoAgain = false;
        }
        //获取表单的value
        let searchFormParams = {};
        let newParams = {};
        let preParams = { "listType": this.listType, "dealtype": this.dealtype, "categoryid": this.selectedTreeKey || params.selectedTreeKey };
        if ((_.has(params, 'fromSuperPage') && params.fromSuperPage == true && params.isSuperSearch == true)) {//pre高级搜索
            searchFormParams = this.formB.getFormParams();
            newParams = { ...searchFormParams, "isSuper": "1" };
        } else {
            searchFormParams = this.form.getFormParams();
        }
        //顶部表单搜索
        if (_.has(searchFormParams, "selectKey")) {
            let omitNewParams = _.omit(searchFormParams, ['selectKey']);
            let keys = Object.keys(omitNewParams);
            if (searchFormParams["selectKey"] == "") {
                let pick = _.pick(searchFormParams, keys);
                newParams = _.mapKeys(pick, (value, key) => {
                    return key == keys[keys.length - 1] ? "selectValue" : key
                });
            } else if (searchFormParams["selectKey"]) {
                newParams = _.mapKeys(searchFormParams, (value, key) => {
                    return key == keys[keys.length - 1] ? "selectValue" : key
                })
            }
        }
        newParams = { ...preParams, ...params, ...newParams };
        this.apisType(newParams).then(data => {
            this.tableTaskStore.getDatas(data.sessionkey, 1);
            this.status.loading = false;
        })
        this.formB.resetForm()
    }

    /**
     * 任务台账基本搜索
     */
    @action
    doSearch2 = (params) => {
        let newParams = { "dealtype": this.dealtype, "fromSuperPage": true, "isSuper": "1", "isSuperPage": true, "categoryid": this.selectedTreeKey, ...params }
        this.apisType(newParams).then(data => {
            this.tableTaskStore.getDatas(data.sessionkey, 1);
            this.status.loading = false;
        })
        this.formB.resetForm()
    }

    //滑出权限
    @action
    getTaskRight = (params, callback = false) => {
        Apis.getTaskRight(params).then(data => {
            if (parseInt(data.status) == 1 && data.isRight == true) {
                this.hasTaskRight = true;
                callback();
            } else {
                this.status.showSlideModal = false;
                this.hasTaskRight = false;
                message.warning(getLabel('2011', "没有权限"));
            }
            this.status.loading = false;
        })
            .catch(error => {
                message.error(error);
            });
    }
    /**
     * 清理滑出区域
     */
    @action
    clearSlide = () => {
        this.slideStatu = {
            id: "",
            rightMenu: [],
            quickBtn: [],
            progress: 0
        }
    }
    /**
     * 展示滑出内容
     */
    @action
    showSlideModal = (bool) => {
        this.status.showSlideModal = bool;
        if (!bool) {
            this.clearSlide();
        }
    }

    /**
     * 触发方式（0卡片触发、1触发流程）（key 0新建、1汇报、2分解、3催办、4变更）
     * @param {*} params
     */
    @action
    getActionSetting(taskId, key) {
        let _this = this;
        Apis.getActionSetting({ "taskid": taskId, "actiontype": key }).then(data => {
            if (parseInt(data.status) == 1) {
                if (data.isShowModel) {
                    _this.showModel(taskId, key);
                } else {
                    if (data.status == "-1") {
                        message.error(data.error);
                    } else {
                        window.open("/spa/workflow/index_form.jsp#/main/workflow/req?requestid=" + data.newrequestid + "&workflowid=" + data.flowid + "&taskid=" + taskId + "&actiontype=" + key);
                    }
                }
            } else {
                message.error(data.error);
            }
        }).catch(error => {
            message.error(error);
        });
    }
    @action
    getcolumnsNum(num) {
        this.columnsNum = num;
    }
    @action
    clear() {
        this.selectedTreeKey = 0;
    }

    exportGovernExcel = (ids, modelType, title2, content, categoryid, type) => {
        let Base64 = WeaTools.Base64;
        this.modelType = modelType;
        let _this = this;
        Modal.confirm({
            cancelText: `${getLabel(201, '取消')}`,
            okText: `${getLabel(826, '确定')}`,
            title: title2,
            content: content,
            onOk() {
                let taskids = ids.join(",");
                let url = "/api/govern/task/exportGovernExcel?type=" + type + "&categoryid=" + categoryid + "&taskids=" + taskids + "&sheetname=" +encodeURIComponent(Base64.encode(_this.title)) + "&dataType=" + _this.dataType ;
                window.location.href = url;
            },
            onCancel() { },
        });
    }
    
    @action
    getCardStorefun = (store)=>{
        this.Card = store;    
    }

}
